package cn.kent.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.Yaml;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("")
public class TestController {


    @GetMapping("/hello")
    public String test01() {
        log.info("进入了test01方法，path = /test/hello");
        return "/test/hello";
    }
    @GetMapping("/map/getPgm1")
    public ResponseEntity<FileSystemResource> getPgm(String fileName, HttpServletResponse response) {
        log.info("下载文件名称：{}", fileName);
        //InputStream in = null;
        //InputStream in = mapServiceImpl.getPgmFile(fileName);
        //OutputStream out = null;
        try {
            //response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); // 设置文件头
            File file = new File(getPgmFilePath(fileName));
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename=" + fileName);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Last-Modified", new Date().toString());
            headers.add("ETag", String.valueOf(System.currentTimeMillis()));
            return org.springframework.http.ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new FileSystemResource(file));

        } catch (Exception e) {
            e.printStackTrace();
            log.info("dfsId:{}下载文件失败，cause:{}", fileName, e);
        } finally {
        }
        return org.springframework.http.ResponseEntity.status(200).build();
    }

    @PostMapping("/hello")
    public String test02(@RequestBody String id) {
        log.info("进入了test02方法-post请求，path = /test/hello");
        log.info("request Body = " + id);
        return "/test/hello-post";
    }

    public String getPgmFilePath(String fileName) {
        String jmapPath =  fileName;
        //FileReader fileReader = FileReader.create(new File(jmapPath));
        return jmapPath;
    }
    @GetMapping("/map/getMapConfig")
    public ResponseVo getMapConfig(String fileName) {
        fileName = fileName.replace(".pgm", ".yaml");
        fileName = fileName.replace(".PGM", ".yaml");
        String jmapPath = "/map/" + fileName;
        // 使用ClassPathResource获取资源文件
        ClassPathResource resource = new ClassPathResource("map/" + fileName);

        try (InputStream inputStream = resource.getInputStream()) {
            Yaml yaml = new Yaml();
            Object data = yaml.load(inputStream);
            JSONObject jsonObject = JSONUtil.parseObj(data);
            return new ResponseVo().success(jsonObject);
        } catch (IOException e) {
            log.error("读取配置文件失败：", e);
            return new ResponseVo().fail("文件不存在");
        }
    }
    @GetMapping("/map/getPgm")
    public org.springframework.http.ResponseEntity<FileSystemResource> downloadFile(String fileName, HttpServletResponse response) {
        log.info("下载文件名称：{}", fileName);
        //InputStream in = null;
        //InputStream in = mapServiceImpl.getPgmFile(fileName);
        //OutputStream out = null;
        try {
            //response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); // 设置文件头
            ClassPathResource resource = new ClassPathResource("map/" + fileName);
            File file = resource.getFile();;
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename=" + fileName);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Last-Modified", new Date().toString());
            headers.add("ETag", String.valueOf(System.currentTimeMillis()));
            return org.springframework.http.ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new FileSystemResource(file));

        } catch (Exception e) {
            e.printStackTrace();
            log.info("dfsId:{}下载文件失败，cause:{}", fileName, e);
        } finally {
        }
        return org.springframework.http.ResponseEntity.status(200).build();
    }

    @GetMapping("/map/getMapPath")
    public ResponseVo getMapPath(String fileName) {
        JSONObject data = null;
        try {
            data = getMapPath1(fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new ResponseVo().success(data);
    }
    public JSONObject getMapPath1(String fileName) throws IOException {
        fileName = fileName.replace(".pgm", ".path");
        fileName = fileName.replace(".PGM", ".path");
        ClassPathResource resource = new ClassPathResource("map/" + fileName);
        File file = resource.getFile();;

        if (file.exists()) {
            FileReader fileReader = FileReader.create(file);
            try {
                JSONObject jsonObject = JSONUtil.parseObj(fileReader.readString());
                return jsonObject;
            }
            catch (Exception e) {
                throw new RuntimeException("网络文件存在问题，解析失败");
                //e.printStackTrace();
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("map", null);
        jsonObject.put("nodes", new ArrayList<>());
        jsonObject.put("edges", new ArrayList<>());
        return jsonObject;
    }

    @PostMapping("/map/saveMapData")
    public ResponseVo saveMapData(@RequestParam("fileName") String fileName, @RequestParam("json") String json) {
        Boolean data = null;
        try {
            data = saveMapDataS(fileName, json);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
            return new ResponseVo<>();
        }
        return new ResponseVo().success(data);
    }

    public Boolean saveMapDataS(String fileName, String json) throws IOException {
        JSONObject jsonObject = JSONUtil.parseObj(json);
        if (fileName.endsWith(".pgm")) {
            fileName = fileName.replace(".pgm", ".path");
        }
//        String path = redisUtil.get("jmap_path") + "/jmaps/" + fileName;
        ClassPathResource resource = new ClassPathResource("map/" + fileName);
        File file = resource.getFile();;
        FileUtil.writeString(jsonObject.toStringPretty(), file, CharsetUtil.UTF_8);
        return true;
    }
}
